package com.base.component.aws.s3.cloudfront;

import static java.nio.charset.StandardCharsets.UTF_8;

import java.net.URI;
import java.security.InvalidKeyException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Base64;

import com.gitee.magic.core.exception.ApplicationException;

public class SingerUrl {
	
	public static String getSignUrl(String resourceUrl,String keyPairId,String privateKeyString) {
		PrivateKey privateKey;
		try {
			privateKey = Rsa.privateKeyFromPkcs1(Base64.getDecoder().decode(privateKeyString));
		} catch (InvalidKeySpecException e) {
			throw new ApplicationException(e);
		}
        Instant expirationDate = Instant.now().plus(7, ChronoUnit.DAYS);
        String cannedPolicy = SigningUtils.buildCannedPolicy(resourceUrl, expirationDate);
        byte[] signatureBytes;
		try {
			signatureBytes = SigningUtils.signWithSha1Rsa(cannedPolicy.getBytes(UTF_8), privateKey);
		} catch (InvalidKeyException e) {
			throw new ApplicationException(e);
		}
        String urlSafeSignature = SigningUtils.makeBytesUrlSafe(signatureBytes);
        URI uri = URI.create(resourceUrl);
        String protocol = uri.getScheme();
        String encodedPath = uri.getRawPath()
                             + (uri.getQuery() != null ? "?" + uri.getRawQuery() + "&" : "?")
                             + "Expires=" + expirationDate.getEpochSecond()
                             + "&Signature=" + urlSafeSignature
                             + "&Key-Pair-Id=" + keyPairId;
        String url=protocol+"://"+uri.getHost()+encodedPath;
        return url;
	}
	
}
